package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.demo.entity.Post;
import com.example.demo.entity.PostLike;
import com.example.demo.mapper.PostLikeMapper;
import com.example.demo.mapper.PostMapper;
import com.example.demo.service.PostLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class PostLikeServiceImpl implements PostLikeService {

    @Autowired
    private PostLikeMapper postLikeMapper;

    @Autowired
    private PostMapper postMapper;

    @Override
    @Transactional
    public boolean likePost(Long postId, Long userId) {
        // 检查是否已点赞
        if (isPostLiked(postId, userId)) {
            return false;
        }

        // 创建点赞记录
        PostLike postLike = new PostLike();
        postLike.setPostId(postId);
        postLike.setUserId(userId);
        postLike.setCreateTime(LocalDateTime.now());
        postLikeMapper.insert(postLike);

        // 更新帖子点赞数
        LambdaUpdateWrapper<Post> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Post::getId, postId)
                    .setSql("like_count = like_count + 1");
        return postMapper.update(null, updateWrapper) > 0;
    }

    @Override
    @Transactional
    public boolean unlikePost(Long postId, Long userId) {
        // 删除点赞记录
        LambdaQueryWrapper<PostLike> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PostLike::getPostId, postId)
                   .eq(PostLike::getUserId, userId);
        if (postLikeMapper.delete(queryWrapper) == 0) {
            return false;
        }

        // 更新帖子点赞数
        LambdaUpdateWrapper<Post> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Post::getId, postId)
                    .ge(Post::getLikeCount, 1)  // 确保点赞数不会小于0
                    .setSql("like_count = like_count - 1");
        return postMapper.update(null, updateWrapper) > 0;
    }

    @Override
    public boolean isPostLiked(Long postId, Long userId) {
        LambdaQueryWrapper<PostLike> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PostLike::getPostId, postId)
                   .eq(PostLike::getUserId, userId);
        return postLikeMapper.selectCount(queryWrapper) > 0;
    }
} 